package org.ykh.common.utils;

import java.util.*;

/**
 * @author ykh
 */
public class StringUtils  {

    /**
     * 将控制字符转换为转义字符
     * @param s
     * @return
     */
    public static String escapeControlCharacters(char[] s) {
        if (s == null) {
            throw new NullPointerException();
        }
        StringBuilder escaped = new StringBuilder();
        StringBuilder subEscaped = new StringBuilder();
        StringBuilder sub = new StringBuilder();
        for (char c : s) {
            if (Character.isISOControl(c)) {
                // 转换控制字符为对应的转义序列
                switch (c) {
                    case '\b':
                        subEscaped.append("\\b");  // 退格
                        break;
                    case '\t':
                        subEscaped.append("\\t");  // 制表符
                        break;
                    case '\n':
                        subEscaped.append("\\n");  // 换行
                        break;
                    case '\r':
                        subEscaped.append("\\r");  // 回车
                        break;
                    case '\f':
                        subEscaped.append("\\f");  // 换页
                        break;
                    default:
                        // 对于其他控制字符，使用Unicode转义序列形式表示
                        subEscaped.append(String.format("\\u%04x", (int) c));
                        break;
                }
                sub.append(c);
            } else if (subEscaped.length() != 0 && sub.length() != 0) {
                escaped.append(subEscaped);
                escaped.append(sub);
                subEscaped.setLength(0);
                sub.setLength(0);
            } else {
                escaped.append(c);
            }

        }

        if (subEscaped.length() != 0 && sub.length() != 0) {
            escaped.append(subEscaped);
            escaped.append(sub);
        }

        return escaped.toString();
    }

    public static String escapeControlCharacters(String s) {
        return escapeControlCharacters(s.toCharArray());
    }
}
